package ua.sumdu.LukyanovChalyi.Client;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.log4j.*;
import org.apache.log4j.xml.*;

public class Client implements Runnable {

    private static final Logger logger = Logger.getLogger(Client.class);
    private Socket socket;
    private View view;

    public Client(View view, String host, int port) throws IOException {
        DOMConfigurator.configure("log4j.xml");
        socket = new Socket(host, port);
        this.view = view;
    }

    @Override
    public void run() {
        try {
            Thread from = new Thread(new FromServerThread(socket.getInputStream(), view));
            Thread to = new Thread(new ToServerThread(socket.getOutputStream(), view));
            from.start();
            to.start();
        } catch (FileNotFoundException e) {
            view.showException("Can't open file with logger settings!", e);
        } catch (IOException e) {
            view.showException("Server doesn't work or disconnected. Exit.", e);
        }
    }

    public static void main(String[] args) {
        View view = new View();
        if (args.length != 2) {
            logger.info("Wrong parametrs! Use 'host' 'port'.");
            view.showMessage("Use host port for run client!");
            System.exit(0);
        }
        int port = 0;
        try {
            port = Integer.parseInt(args[1]);
            if (port <= 0 || port > 65535) {
                logger.info("Port cant be less zero or bigger that 65535");
                view.showMessage("Port cant be less zero or bigger that 65535");
                System.exit(0);
            }
        } catch (NumberFormatException e) {
            view.showException("Port must be number!", e);
            System.exit(0);
        }

        Client client;
        try {
            client = new Client(view, args[0], port);
            new Thread(client).start();
        } catch (UnknownHostException e) {
            view.showException("Unknown host. Exit!", e);
        } catch (IOException ex) {
            view.showException("If it's first start, may be you use wrong port."
                    + "By the way, can't connect to server. Exit.", ex);
        }

    }
}
